﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Core;
using DataAccessObject.Hibernate;
using log4net.Config;
using NHibernate;
using NHibernate.Context;

namespace WebAPI
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            Bootstrapper.Run();
            InitLog4net();
            //Log.Info("Application Started");
        }

        protected void Application_End(object sender, EventArgs e)
        {
            IoC.Reset();
            //Log.Warning("Application Ended");
        }

        //public void Init(HttpApplication context)
        //{
        //    context.BeginRequest += new EventHandler(Application_BeginRequest);
        //    context.EndRequest += new EventHandler(Application_EndRequest);
        //}

        //private void Application_BeginRequest(object sender, EventArgs e)
        //{
        //    //CurrentSessionContext.Bind(ExampleApplication.SessionFactory.OpenSession());
        //}

        private void Application_EndRequest(object sender, EventArgs e)
        {
            INhSessionFactory factory = IoC.Resolve<INhSessionFactory>();
            ISession session = CurrentSessionContext.Unbind(factory[SessionContext.Web]);
            if (session != null && session.Transaction.IsActive)
            {
                session.Transaction.Rollback();
            }

            if (session != null)
            {
                session.Close();
            }
        }

        private void InitLog4net()
        {
            string filePath = Server.MapPath("~/Configs/log4net.config");
            FileInfo fileInfo = new FileInfo(filePath);
            XmlConfigurator.ConfigureAndWatch(fileInfo);
        }
    }
}
